import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torchvision
import numpy as np
import torch.nn.functional as F
from torchinfo import summary
import warnings

# 忽略警告信息,避免一些不必要的提示干扰输出
warnings.filterwarnings("ignore")
# 设置中文字体显示及负号显示等绘图相关参数
plt.rcParams['font.sans-serif'] = ['SimHei']# 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False# 用来正常显示负号
plt.rcParams['figure.dpi'] = 100# 图片像素
# 定义设备,检测GPU是否可用,如果可用则使用GPU,否则使用CPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')


class MNISTModelTrainer:
    """
    MNIST模型训练器类,整合了数据加载、模型定义、训练、测试以及结果可视化等功能。
    """
    def __init__(self, data_dir='data', batch_size=32, num_classes=10, learn_rate=1e-2, epochs=2):
        self.data_dir = data_dir# 数据集存放目录
        self.batch_size = batch_size# 批次大小
        self.num_classes = num_classes# 分类的类别数量
        self.learn_rate = learn_rate# 学习率
        self.epochs = epochs# 训练的总轮数
        self.data_loader = self._create_data_loader()# 创建MNIST数据集的数据加载器
        self.model = self._create_model()# 创建模型对象
        from torch.utils.tensorboard import SummaryWriter
        writer = SummaryWriter('run1/fashion_mnist_experiment_1')
        test = torch.ones(1, 1, 28, 28)
        # 先将模型移动到CPU
        model_cpu = self.model.to('cpu')  
        writer.add_graph(model_cpu, test)
        writer.close()
        # 后续训练等操作如果需要GPU再将模型移回相应设备（比如有GPU可用时移回cuda）
        self.model = model_cpu.to(device)
        self.loss_fn = nn.CrossEntropyLoss()# 创建损失函数
        self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.learn_rate)# 创建优化器
        # 用于存储训练过程中的准确率和损失
        self.train_loss = []
        self.train_acc = []
        self.test_loss = []
        self.test_acc = []

    def _create_data_loader(self):
        """
        内部函数,用于创建MNIST数据集的训练集和测试集的数据加载器。
        :return: MNISTDataLoader对象,包含训练集和测试集的数据加载器。
        """
        train_ds = torchvision.datasets.MNIST(self.data_dir,train=True,transform=torchvision.transforms.ToTensor(),download=True)
        test_ds = torchvision.datasets.MNIST(self.data_dir,train=False,transform=torchvision.transforms.ToTensor(),download=True)
        train_dl = torch.utils.data.DataLoader(train_ds,batch_size=self.batch_size,shuffle=True)
        test_dl = torch.utils.data.DataLoader(test_ds,batch_size=self.batch_size)
        return type('MNISTDataLoader', (), {'train_dl': train_dl, 'test_dl': test_dl})()

    def _create_model(self):
        """
        内部函数,用于定义MNIST图像分类模型。
        :return: 定义好的Model对象,包含特征提取和分类相关的网络层。
        """
        class Model(nn.Module):
            def __init__(self, num_classes):
                super().__init__()
                # 特征提取网络
                self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
                self.pool1 = nn.MaxPool2d(2)
                self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
                self.pool2 = nn.MaxPool2d(2)
                # 分类网络
                self.fc1 = nn.Linear(1600, 64)
                self.fc2 = nn.Linear(64, num_classes)

            def forward(self, x):
                x = self.pool1(F.relu(self.conv1(x)))
                x = self.pool2(F.relu(self.conv2(x)))
                x = torch.flatten(x, start_dim=1)
                x = F.relu(self.fc1(x))
                x = self.fc2(x)
                return x

        return Model(self.num_classes).to(device)

    def train_epoch(self):
        """
        在一个训练周期(epoch)内对模型进行训练,计算并返回该周期的训练准确率和训练损失。
        :return: 当前训练周期的训练准确率和训练损失。
        """
        train_dl = self.data_loader.train_dl
        size = len(train_dl.dataset)
        num_batches = len(train_dl)
        train_loss, train_acc = 0, 0

        for X, y in train_dl:
            X, y = X.to(device), y.to(device)
            pred = self.model(X)
            loss = self.loss_fn(pred, y)

            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()

            train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
            train_loss += loss.item()

        train_acc /= size
        train_loss /= num_batches

        return train_acc, train_loss

    def test_epoch(self):
        """
        在测试集上对模型进行评估,计算并返回测试准确率和测试损失。
        :return: 当前测试的测试准确率和测试损失。
        """
        test_dl = self.data_loader.test_dl
        size = len(test_dl.dataset)
        num_batches = len(test_dl)
        test_loss, test_acc = 0, 0

        with torch.no_grad():
            for imgs, target in test_dl:
                imgs, target = imgs.to(device), target.to(device)
                target_pred = self.model(imgs)
                loss = self.loss_fn(target_pred, target)
                test_loss += loss.item()
                test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()
        test_acc /= size
        test_loss /= num_batches
        
        return test_acc, test_loss

    def train(self):
        """
        进行完整的训练过程,多个训练周期的循环,在每个周期内分别进行训练和测试,并记录相关指标。
        """
        for epoch in range(self.epochs):
            # 训练模式
            self.model.train()
            epoch_train_acc, epoch_train_loss = self.train_epoch()
            # 评估模式
            self.model.eval()
            epoch_test_acc, epoch_test_loss = self.test_epoch()
            self.train_acc.append(epoch_train_acc)
            self.train_loss.append(epoch_train_loss)
            self.test_acc.append(epoch_test_acc)
            self.test_loss.append(epoch_test_loss)
            template = 'Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}'
            print(template.format(epoch + 1, epoch_train_acc * 100, epoch_train_loss, epoch_test_acc * 100, epoch_test_loss))
        print('训练完成')
    def save_model(self, model_path='mnist_model.pth'):# 保存模型参数
        torch.save(self.model.state_dict(), model_path)
        
    def plot_training_results(self):
        """
        绘制训练和测试过程中的准确率和损失变化曲线,用于可视化模型训练效果。
        """
        epochs_range = range(self.epochs)
        plt.figure(figsize=(6, 6))  # 可以根据需要调整整个图形的大小
        # 调整子图布局参数，将两个子图垂直摆放，1行2列变为2行1列
        plt.subplot(2, 1, 1)
        plt.plot(epochs_range, self.train_acc, label='Training Accuracy')
        plt.plot(epochs_range, self.test_acc, label='Test Accuracy')
        plt.legend(loc='lower right')
        plt.title('训练和验证准确率')

        plt.subplot(2, 1, 2)
        plt.plot(epochs_range, self.train_loss, label='Training Loss')
        plt.plot(epochs_range, self.test_loss, label='Test Loss')
        plt.legend(loc='upper right')
        plt.title('训练和验证损失')
        plt.show()

if __name__ == "__main__":
    trainer = MNISTModelTrainer()
    trainer.train()
    trainer.save_model()
    trainer.plot_training_results()